package com.digitalchina.lxnsy.activity.old;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.api.BusinessTechnologies;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.CommentVO;
import com.digitalchina.lxnsy.entity.PlanProductVO;
import com.digitalchina.lxnsy.entity.TechnologiesCommentVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.JointImageUrl;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.TechnologiesCommentHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/8/25 16:01
 * 修改备注：
 * ================================================
 */
public class PlantProductionDetailActivity extends BaseActivity implements BGABanner.Adapter<ImageView, String> {


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.et_msg)
    EditText etMsg;
    @Bind(R.id.tv_send)
    TextView tvSend;

    private PlanProductVO.FarmOperationBean vo;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 2;
    private List<TechnologiesCommentVO> voList = new ArrayList<>();
    private String id; // 农事操作ID
    private String type = "4";

    private View view;
    TextView tvTitle;
    TextView tvFinish;
    TextView tvContent;
    LinearLayout layoutVideo;
    LinearLayout layoutFarm;
    LinearLayout layoutExpert;
    LinearLayout layoutMore;
    LinearLayout layoutAgriculture; // 新农艺
    LinearLayout layoutPest; // 病虫草害
    BGABanner banner;

    private String productStandardId = ""; // 标准ID
    private String planId = ""; // 计划ID
    private String phId = ""; // 物候期ID
    private String phaseName = ""; // 物候期NAME

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_plant_production_detail);
        setTitle("农事操作详情");
    }

    @Override
    public void initMember() {

        vo = (PlanProductVO.FarmOperationBean) getIntent().getSerializableExtra("vo");

        if (vo == null)
            return;


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapter(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TechnologiesCommentHolder(parent);
            }
        });

        id = vo.getId();
        planId = vo.getPlanId();
        phaseName = vo.getPhaseName();
        phId = vo.getPhId();
        productStandardId = vo.getProductStandardId();

        view = LayoutInflater.from(this).inflate(R.layout.view_plant_production_detail, null);
        banner = view.findViewById(R.id.banner);
        tvTitle = view.findViewById(R.id.tv_title);
        tvFinish = view.findViewById(R.id.tv_finish);
        tvContent = view.findViewById(R.id.tv_content);
        layoutVideo = view.findViewById(R.id.layout_video);
        layoutMore = view.findViewById(R.id.layout_more);
        layoutFarm = view.findViewById(R.id.layout_farm);
        layoutExpert = view.findViewById(R.id.layout_expert);
        layoutAgriculture = view.findViewById(R.id.layout_agriculture);
        layoutPest = view.findViewById(R.id.layout_pest);


        adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
            @Override
            public View onCreateView(ViewGroup parent) {

                return view;
            }

            @Override
            public void onBindView(View headerView) {


            }
        });


        if (!StringUtil.isStrEmpty(vo.getFarmName()))
            tvTitle.setText(vo.getFarmName());
        if (!StringUtil.isStrEmpty(vo.getOperInstr()))
            tvContent.setText(vo.getOperInstr());

        if (vo.isIsOperation()) {
            tvFinish.setVisibility(View.VISIBLE);
            tvFinish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    BusinessPlan.operationCompleted(PlantProductionDetailActivity.this, planId, id, mHandler);
                }
            });
        }


        if (vo.getFarmOperationPicImageList() != null && vo.getFarmOperationPicImageList().size() > 0) {
            initBanner(vo.getFarmOperationPicImageList());
        }

        if (!StringUtil.isStrEmpty(vo.getVidAddress()))
            layoutVideo.setVisibility(View.VISIBLE);

        BusinessTechnologies.getCommentList(this, id, type, page, limit, mHandler);
    }

    /**
     * 设置顶部轮播图
     */
    private void initBanner(List<PlanProductVO.FarmOperationBean.FarmOperationPicImageListBean> list) {

        List<String> imagesList = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        imagesList.clear();
        titles.clear();
        for (int i = 0; i < list.size(); i++) {
            imagesList.add(JointImageUrl.middleImageUrl(list.get(i).getImage()));
            titles.add("");
        }

        banner.setAdapter(this);
        banner.setData(imagesList, titles);
    }

    @Override
    public void addListener() {

        layoutVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, TechnologyTrainingVideoDetailNewActivity.class, "path", vo.getVidAddress());
            }
        });

        layoutFarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusinessAccount.appOnclick(PlantProductionDetailActivity.this, productStandardId, "12", mHandler);
                Map<String, String> map = new HashMap<>();
                map.put("productionId", planId);
                map.put("phaseName", phaseName);
                map.put("phId", phId);
                map.put("farmOptId", vo.getId());
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, AddFarmingRecordActivityV2.class, "map", map);
            }
        });

        layoutExpert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusinessAccount.appOnclick(PlantProductionDetailActivity.this, productStandardId, "13", mHandler);
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, PlantExpertListActivity.class, "productStandardId", productStandardId);
            }
        });

        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (StringUtil.isEditEmpty(etMsg)) {
                    showToast("请输入评论内容");
                    return;
                }

                if (id != null)
                    BusinessTechnologies.publishComment(PlantProductionDetailActivity.this, id, etMsg.getText().toString(), type, mHandler);
            }
        });

        layoutMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, CommentActivity.class, "CommentVO", new CommentVO(id, "4"));
            }
        });

        //新农艺
        layoutAgriculture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusinessAccount.appOnclick(PlantProductionDetailActivity.this, productStandardId, "14", mHandler);
                // 农事操作ID+生产标准ID
                // 2019年7月5日 15:28:08 改版 只需要生产标准ID
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, NewAgricultureActivity.class, "ID", productStandardId);
            }
        });

        //病虫草害
        layoutPest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusinessAccount.appOnclick(PlantProductionDetailActivity.this, productStandardId, "15", mHandler);
                GotoUtil.gotoActivity(PlantProductionDetailActivity.this, PestListActivity.class, "ID", id + "&" + productStandardId);
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (recyclerView == null)
                    return;

                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_OPERATION_COMPLETED_SUCCESS:
                        showToast("操作完成");
                        tvFinish.setVisibility(View.INVISIBLE);
                        setResult(RESULT_OK);
                        break;
                    case MSG.MSG_OPERATION_COMPLETED_FIELD:
                        showToast(msg.obj.toString());
                        break;

                    case MSG.MSG_GET_COMMENT_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_COMMENT_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        break;
                    case MSG.MSG_PUBLISH_COMMENT_SUCCESS:
                        showToast("评论成功");
                        // 隐藏软键盘
                        InputMethodManager imm = (InputMethodManager) etMsg
                                .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive()) {
                            imm.hideSoftInputFromWindow(etMsg.getApplicationWindowToken(), 0);
                        }
                        etMsg.setText("");
                        BusinessTechnologies.getCommentList(PlantProductionDetailActivity.this, id, type, page, limit, mHandler);
                        break;
                    case MSG.MSG_PUBLISH_COMMENT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        voList = FastJsonUtil.getListBean(object.toString(), "list", TechnologiesCommentVO.class);

//        if (page == 1) { // 刷新
        adapter.clear();
//        }

        adapter.addAll(voList);

//        if (voList != null) {
//            if (voList.size() < limit) {
//                adapter.stopMore();
//            }
//        }
    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
        Glide.with(itemView.getContext())
                .load(model)
                .placeholder(R.drawable.bg_default)
                .error(R.drawable.bg_default)
                .dontAnimate()
                .centerCrop()
                .into(itemView);
    }
}
